package testplan.servlets;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import static com.google.common.base.Preconditions.checkNotNull;

import testplan.entities.User;
import testplan.services.UserService;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class UserServlet extends HttpServlet 
{
	@Inject
	private UserService service;
	
	private static final String ACTION_SESSION = "session";
	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
		final String action = request.getParameter("action");
		checkNotNull(action);
		try
		{
			if(ACTION_SESSION.equals(action))
			{
				doSession(request, response);
			}
		}
		catch(JSONException e)
		{
			throw new RuntimeException(e);
		}
    }

	private void doSession(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException 
	{
		final JSONObject jsonResult = new JSONObject();
		final User sessionUser = (User) request.getSession().getAttribute("user");
		if(sessionUser == null)
		{
			jsonResult.put("login", false);
		}
		else
		{
			jsonResult.put("login", true);
			jsonResult.put("user", new JSONObject(sessionUser));
		}
		response.getOutputStream().println(jsonResult.toString());
	}

}
